package com.ruoyi.web.controller.talent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.system.domain.RoleTalentPermission;
import com.ruoyi.system.domain.TalentTemplate;
import com.ruoyi.system.domain.TalentTemplateField;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.service.IRoleTalentPermissionService;
import com.ruoyi.system.service.ITalentTemplateService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysDictTypeService;

/**
 * 岗位人才库数据管理 控制器
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/talent/data")
public class TalentDataController extends BaseController
{
    @Autowired
    private ITalentTemplateService talentTemplateService;

    @Autowired
    private IRoleTalentPermissionService roleTalentPermissionService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    /**
     * 获取部门-岗位树（支持权限控制）
     */
    @GetMapping("/tree")
    public AjaxResult getDeptPostTree(@RequestParam(value = "searchValue", required = false) String searchValue)
    {
        boolean isAdmin = SecurityUtils.getLoginUser().getUser().isAdmin();

        // 查询部门列表（受数据权限控制）
        SysDept deptQuery = new SysDept();
        if (searchValue != null && !searchValue.trim().isEmpty()) {
            deptQuery.setDeptName(searchValue);
        }
        List<SysDept> depts = deptService.selectDeptList(deptQuery);

        // 构建部门树
        List<SysDept> deptTree = deptService.buildDeptTree(depts);

        // 为每个部门挂载岗位节点
        attachPostsToTree(deptTree, searchValue);

        Map<String, Object> result = new HashMap<>();
        result.put("isAdmin", isAdmin);
        result.put("tree", deptTree);
        return success(result);
    }

    /**
     * 为部门树挂载岗位节点
     */
    private void attachPostsToTree(List<SysDept> deptNodes, String searchValue)
    {
        if (deptNodes == null) return;

        for (SysDept dept : deptNodes)
        {
            // 递归处理子部门
            if (dept.getChildren() != null && !dept.getChildren().isEmpty())
            {
                attachPostsToTree(dept.getChildren(), searchValue);
            }

            // 直接根据部门ID查询该部门下的岗位
            SysPost postQuery = new SysPost();
            postQuery.setDeptId(dept.getDeptId());
            postQuery.setStatus("0"); // 只查询正常状态的岗位
            List<SysPost> deptPosts = postService.selectPostList(postQuery);

            // 为该部门创建岗位节点
            List<SysDept> postNodes = new ArrayList<>();
            for (SysPost post : deptPosts)
            {
                // 如果有搜索关键字，过滤岗位
                if (searchValue != null && !searchValue.trim().isEmpty())
                {
                    if (!post.getPostName().contains(searchValue))
                    {
                        continue;
                    }
                }

                // 创建岗位节点（用SysDept结构表示）
                SysDept postNode = new SysDept();
                postNode.setDeptId(post.getPostId());
                postNode.setDeptName(post.getPostName());
                // 用status字段标记这是岗位节点，存储完整的postCode
                postNode.setStatus("POST:" + post.getPostCode());
                postNode.setParentId(dept.getDeptId());
                postNodes.add(postNode);
            }

            // 将岗位节点添加到部门的children中
            if (!postNodes.isEmpty())
            {
                if (dept.getChildren() == null)
                {
                    dept.setChildren(postNodes);
                }
                else
                {
                    dept.getChildren().addAll(postNodes);
                }
            }
        }
    }

    /**
     * 根据岗位编码获取人才库字段和数据（支持分页）
     */
    @GetMapping("/{postCode}")
    public AjaxResult getData(@PathVariable("postCode") String postCode,
                             @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                             @RequestParam(value = "pageSize", defaultValue = "100") Integer pageSize,
                             @RequestParam(value = "sheetName", required = false) String sheetName)
    {
        // 根据岗位编码查询模板
        TalentTemplate query = new TalentTemplate();
        query.setPostCode(postCode);
        List<TalentTemplate> templates = talentTemplateService.selectTalentTemplateList(query);
        
        if (templates.isEmpty())
        {
            return error("未找到该岗位的人才库模板，请先设置模板");
        }

        TalentTemplate template = templates.get(0);
        
        // 查询模板所有字段
        List<TalentTemplateField> allFields = talentTemplateService.selectFieldsByTemplateId(template.getId());
        
        // 判断当前用户是否是admin
        boolean isAdmin = SecurityUtils.getLoginUser().getUser().isAdmin();
        
        List<Map<String, Object>> fieldConfigs = new ArrayList<>();
        List<String> allowedFields = new ArrayList<>();
        
        if (isAdmin)
        {
            // admin用户：返回所有字段，全部可读写
            for (TalentTemplateField field : allFields)
            {
                Map<String, Object> fieldConfig = new HashMap<>();
                fieldConfig.put("fieldName", field.getFieldName());
                fieldConfig.put("fieldLabel", field.getFieldLabel());
                fieldConfig.put("fieldType", field.getFieldType());
                fieldConfig.put("sortOrder", field.getSortOrder());
                fieldConfig.put("isRequired", field.getIsRequired());
                fieldConfig.put("columnWidth", field.getColumnWidth());
                fieldConfig.put("cellTypeConfig", field.getCellTypeConfig()); // 添加单元格类型配置
                fieldConfig.put("permissionType", "1"); // admin全部可读写
                fieldConfigs.add(fieldConfig);
                allowedFields.add(field.getFieldName());
            }
        }
        else
        {
            // 非admin用户：根据权限过滤
            Long roleId = SecurityUtils.getLoginUser().getUser().getRoles().get(0).getRoleId();
            List<RoleTalentPermission> permissions = roleTalentPermissionService
                .selectPermissionsByRoleAndTable(roleId, template.getTableName());
            
            for (TalentTemplateField field : allFields)
            {
                String permissionType = getFieldPermission(field.getFieldName(), permissions);
                if (permissionType != null)
                {
                    Map<String, Object> fieldConfig = new HashMap<>();
                    fieldConfig.put("fieldName", field.getFieldName());
                    fieldConfig.put("fieldLabel", field.getFieldLabel());
                    fieldConfig.put("fieldType", field.getFieldType());
                    fieldConfig.put("sortOrder", field.getSortOrder());
                    fieldConfig.put("isRequired", field.getIsRequired());
                    fieldConfig.put("columnWidth", field.getColumnWidth());
                    fieldConfig.put("cellTypeConfig", field.getCellTypeConfig()); // 添加单元格类型配置
                    fieldConfig.put("permissionType", permissionType);
                    fieldConfigs.add(fieldConfig);
                    allowedFields.add(field.getFieldName());
                }
            }
        }

        // 检查是否有"招聘状态"字段
        TalentTemplateField recruitmentStatusField = null;
        String recruitmentStatusFieldName = null;
        
        System.out.println("=== 检查招聘状态字段 ===");
        System.out.println("请求参数 - sheetName: " + sheetName);
        
        for (TalentTemplateField field : allFields) {
            if ("招聘状态".equals(field.getFieldLabel())) {
                recruitmentStatusField = field;
                recruitmentStatusFieldName = field.getFieldName();
                System.out.println("✓ 找到招聘状态字段: " + field.getFieldName());
                break;
            }
        }
        
        // 查询所有数据
        List<Map<String, Object>> allData = talentTemplateService.selectDynamicTableData(template.getTableName());
        
        Map<String, Object> result = new HashMap<>();
        result.put("template", template);
        result.put("fields", fieldConfigs);
        
        if (recruitmentStatusField != null && StringUtils.isNotNull(recruitmentStatusFieldName)) {
            // 有招聘状态字段，支持多sheet模式
            System.out.println("✓ 检测到招聘状态字段，启用多sheet模式");
            
            // 查询招聘状态字典数据
            List<SysDictData> dictDataList = dictTypeService.selectDictDataByType("recruitment_status");
            
            if (dictDataList != null && !dictDataList.isEmpty()) {
                // 构建可用sheet列表
                List<Map<String, Object>> availableSheets = new ArrayList<>();
                for (SysDictData dictData : dictDataList) {
                    Map<String, Object> sheetInfo = new HashMap<>();
                    sheetInfo.put("name", dictData.getDictLabel());
                    sheetInfo.put("value", dictData.getDictValue());
                    availableSheets.add(sheetInfo);
                }
                
                // 确定当前要显示的sheet
                String currentSheetValue = null;
                String currentSheetName = null;
                
                if (StringUtils.isNotNull(sheetName)) {
                    // 根据sheetName参数查找对应的value
                    for (SysDictData dictData : dictDataList) {
                        if (dictData.getDictLabel().equals(sheetName)) {
                            currentSheetValue = dictData.getDictValue();
                            currentSheetName = dictData.getDictLabel();
                            break;
                        }
                    }
                }
                
                // 如果没找到或没指定，使用第一个
                if (currentSheetValue == null && !dictDataList.isEmpty()) {
                    currentSheetValue = dictDataList.get(0).getDictValue();
                    currentSheetName = dictDataList.get(0).getDictLabel();
                }
                
                System.out.println("当前sheet: " + currentSheetName + " (值=" + currentSheetValue + ")");
                
                // 过滤当前sheet的数据
                List<Map<String, Object>> currentSheetData = new ArrayList<>();
                for (Map<String, Object> row : allData) {
                    Object rowStatus = row.get(recruitmentStatusFieldName);
                    if (currentSheetValue.equals(String.valueOf(rowStatus))) {
                        // 根据权限过滤数据字段
                        Map<String, Object> filteredRow = new HashMap<>();
                        
                        if (row.containsKey("id")) {
                            filteredRow.put("id", row.get("id"));
                        }
                        
                        for (String fieldName : allowedFields) {
                            if (row.containsKey(fieldName)) {
                                filteredRow.put(fieldName, row.get(fieldName));
                            }
                        }
                        
                        currentSheetData.add(filteredRow);
                    }
                }
                
                System.out.println("当前sheet匹配到 " + currentSheetData.size() + " 条数据");
                
                // 分页处理
                int total = currentSheetData.size();
                int fromIndex = (pageNum - 1) * pageSize;
                int toIndex = Math.min(fromIndex + pageSize, total);
                
                List<Map<String, Object>> pagedData;
                if (fromIndex >= total) {
                    pagedData = new ArrayList<>();
                } else {
                    pagedData = currentSheetData.subList(fromIndex, toIndex);
                }
                
                // 返回单sheet格式数据
                result.put("data", pagedData);
                result.put("total", total);
                result.put("pageNum", pageNum);
                result.put("pageSize", pageSize);
                result.put("availableSheets", availableSheets);
                result.put("currentSheet", currentSheetName);
                
            } else {
                // 没有字典数据，回退到单sheet模式
                System.out.println("⚠️  字典数据为空，回退到单sheet模式");
                
                int total = allData.size();
        
        // 使用PageHelper进行分页（手动分页）
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);
        
        List<Map<String, Object>> pagedData;
        if (fromIndex >= total) {
            pagedData = new ArrayList<>();
        } else {
            pagedData = allData.subList(fromIndex, toIndex);
        }
        
        // 根据权限过滤数据字段
        List<Map<String, Object>> filteredData = new ArrayList<>();
                for (Map<String, Object> row : pagedData) {
            Map<String, Object> filteredRow = new HashMap<>();
            
                    if (row.containsKey("id")) {
                filteredRow.put("id", row.get("id"));
            }
            
                    for (String fieldName : allowedFields) {
                        if (row.containsKey(fieldName)) {
                    filteredRow.put(fieldName, row.get(fieldName));
                }
            }
            
            filteredData.add(filteredRow);
        }

        result.put("data", filteredData);
        result.put("total", total);
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);
            }
            
        } else {
            // 没有招聘状态字段，返回默认单sheet
            System.out.println("未检测到招聘状态字段，使用默认单sheet模式");
            
            int total = allData.size();
            
            // 使用PageHelper进行分页（手动分页）
            int fromIndex = (pageNum - 1) * pageSize;
            int toIndex = Math.min(fromIndex + pageSize, total);
            
            List<Map<String, Object>> pagedData;
            if (fromIndex >= total) {
                pagedData = new ArrayList<>();
            } else {
                pagedData = allData.subList(fromIndex, toIndex);
            }
            
            // 根据权限过滤数据字段
            List<Map<String, Object>> filteredData = new ArrayList<>();
            for (Map<String, Object> row : pagedData) {
                Map<String, Object> filteredRow = new HashMap<>();
                
                if (row.containsKey("id")) {
                    filteredRow.put("id", row.get("id"));
                }
                
                for (String fieldName : allowedFields) {
                    if (row.containsKey(fieldName)) {
                        filteredRow.put(fieldName, row.get(fieldName));
                    }
                }
                
                filteredData.add(filteredRow);
            }
            
            result.put("data", filteredData);
            result.put("total", total);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
        }

        return success(result);
    }

    /**
     * 保存岗位人才库数据
     */
    @Log(title = "岗位人才库数据", businessType = BusinessType.UPDATE)
    @PostMapping("/{postCode}")
    public AjaxResult saveData(@PathVariable("postCode") String postCode, 
                               @RequestBody List<Map<String, Object>> dataList)
    {
        // 根据岗位编码查询模板
        TalentTemplate query = new TalentTemplate();
        query.setPostCode(postCode);
        List<TalentTemplate> templates = talentTemplateService.selectTalentTemplateList(query);
        
        if (templates.isEmpty())
        {
            return error("未找到该岗位的人才库模板");
        }

        TalentTemplate template = templates.get(0);
        
        // 判断当前用户是否是admin
        boolean isAdmin = SecurityUtils.getLoginUser().getUser().isAdmin();
        
        List<Map<String, Object>> filteredDataList;
        
        if (isAdmin)
        {
            // admin用户：不过滤字段，直接保存所有数据
            filteredDataList = dataList;
        }
        else
        {
            // 非admin用户：根据权限过滤
            Long roleId = SecurityUtils.getLoginUser().getUser().getRoles().get(0).getRoleId();
            List<RoleTalentPermission> permissions = roleTalentPermissionService
                .selectPermissionsByRoleAndTable(roleId, template.getTableName());

            // 获取有写权限的字段列表
            List<String> writableFields = new ArrayList<>();
            for (RoleTalentPermission permission : permissions)
            {
                if ("1".equals(permission.getPermissionType())) // 1表示读写权限
                {
                    writableFields.add(permission.getFieldName());
                }
            }

            if (writableFields.isEmpty())
            {
                return error("您没有任何字段的修改权限");
            }

            // 过滤数据，只保留有写权限的字段
            filteredDataList = new ArrayList<>();
            for (Map<String, Object> dataRow : dataList)
            {
                Map<String, Object> filteredRow = new HashMap<>();
                
                if (dataRow.containsKey("id"))
                {
                    filteredRow.put("id", dataRow.get("id"));
                }
                
                for (String fieldName : writableFields)
                {
                    if (dataRow.containsKey(fieldName))
                    {
                        filteredRow.put(fieldName, dataRow.get(fieldName));
                    }
                }
                
                if (filteredRow.size() > 1 || !filteredRow.containsKey("id"))
                {
                    filteredDataList.add(filteredRow);
                }
            }

            if (filteredDataList.isEmpty())
            {
                return error("没有可保存的数据");
            }
        }

        // 检查招聘状态字段必填校验
        validateRecruitmentStatus(template, filteredDataList);

        // 确保每行包含模板名称（动态表的非空字段）
        if (filteredDataList != null && !filteredDataList.isEmpty())
        {
            for (Map<String, Object> row : filteredDataList)
            {
                if (!row.containsKey("template_name") || row.get("template_name") == null)
                {
                    row.put("template_name", template.getPostName());
                }
            }
        }

        // 保存数据
        int result = talentTemplateService.saveDynamicTableData(template.getTableName(), filteredDataList);
        return toAjax(result);
    }

    /**
     * 验证招聘状态字段必填
     * 
     * @param template 模板信息
     * @param dataList 要保存的数据列表
     */
    private void validateRecruitmentStatus(TalentTemplate template, List<Map<String, Object>> dataList) {
        // 查询模板字段，检查是否有招聘状态字段
        List<TalentTemplateField> fields = talentTemplateService.selectFieldsByTemplateId(template.getId());
        
        // 查找招聘状态字段
        TalentTemplateField recruitmentStatusField = null;
        String recruitmentStatusFieldName = null;
        
        for (TalentTemplateField field : fields) {
            if ("招聘状态".equals(field.getFieldLabel())) {
                recruitmentStatusField = field;
                recruitmentStatusFieldName = field.getFieldName();
                break;
            }
        }
        
        // 如果存在招聘状态字段，进行必填校验
        if (recruitmentStatusField != null && recruitmentStatusFieldName != null) {
            System.out.println("检测到招聘状态字段，开始必填校验: " + recruitmentStatusFieldName);
            
            for (int i = 0; i < dataList.size(); i++) {
                Map<String, Object> row = dataList.get(i);
                Object recruitmentStatusValue = row.get(recruitmentStatusFieldName);
                
                // 检查招聘状态字段是否为空
                if (recruitmentStatusValue == null || 
                    (recruitmentStatusValue instanceof String && ((String) recruitmentStatusValue).trim().isEmpty())) {
                    
                    String errorMessage = String.format("第%d行招聘状态字段不能为空", i + 1);
                    System.err.println("招聘状态字段校验失败: " + errorMessage);
                    throw new ServiceException(errorMessage);
                }
                
                System.out.println(String.format("第%d行招聘状态校验通过: %s", i + 1, recruitmentStatusValue));
            }
            
            System.out.println("招聘状态字段必填校验全部通过");
        } else {
            System.out.println("未检测到招聘状态字段，跳过必填校验");
        }
    }

    /**
     * 获取字段权限
     * 
     * @param fieldName 字段名
     * @param permissions 权限列表
     * @return 权限类型 1=有权限（可见可编辑） null=无权限（不可见）
     */
    private String getFieldPermission(String fieldName, List<RoleTalentPermission> permissions)
    {
        for (RoleTalentPermission permission : permissions)
        {
            if (fieldName.equals(permission.getFieldName()))
            {
                return permission.getPermissionType();
            }
        }
        return null;
    }
}